/////////////////////旅游攻略,旅游游记/////////////////////////////////
const config = require('../config');

module.exports = function (app, query, jwt) {

  /**
   * 请求GET
   * 参数：tag 按照 标签查询（出境游,国内游 购物圣地 ...）
   *       state 按照 分类查询（-1所有，0攻略，2游记）
   *       pageSize 一页显示的数据条数
   *       current 页码
   */
  app.get('/travelarticleList', jwt({ secret: config.secret, credentialsRequired: false }), function (req, res, next) {
    let { tag, state, title, pageSize, current, self } = req.query;
    let { userId } = req.user;
    console.log(state);
    current = Number(current);
    pageSize = Number(pageSize);

    if (pageSize === NaN) {
      pageSize = 10
    }
    if (current === NaN) {
      current = 1
    }

    let sql = `select * from article`;
    let params = [];

    //按照 标签查询（出境游,国内游 购物圣地 ...）
    if (!!tag) {
      params.push(`class_tag='${tag}'`)
    }

    //标题模糊查询
    if (!!title) {
      params.push(`title like '%${title}%'`)
    }

    //按照 分类查询（-1所有，0攻略，2游记）
    if (!!state) {
      if (state === '-1') {
        params.push(`state in (0,2)`)
      } else {
        params.push(`state in (${state})`)
      }
    }

    //只看自己
    if (self === 'true') {
      params.push(`author_id=${userId}`)
    }
    if (params.length > 0) {
      sql += ` where ` + params.join(' and ');
    }
    sql += ` order by date desc limit ${pageSize * (current - 1)},${pageSize} ;SELECT FOUND_ROWS();`;
    console.log(sql)
    query(sql, function (err, rows, fields) {
      if (err) {
        const json = {
          code: false,
          message: err.message
        };
        console.log(json);
        res.json(json);
      } else {
        console.log(rows)
        if (rows[1] && rows[1].length > 0) {
          let list = Array.from(rows[0]);
          const data = {
            current,
            pageSize,
            total: rows[1][0]['FOUND_ROWS()'],
            list
          }
          const json = {
            code: true,
            message: '查询成功',
            data
          };
          console.log(json);
          res.json(json);
        }
      }
    });

  });


  //发表文章
  app.post('/travelarticle', jwt({ secret: config.secret }), function (req, res, next) {
    let { title, tag, text, state } = req.body;
    const { userId, username } = req.user;
    state = Number(state) ? Number(state) : 0;
    const params = {
      title,
      author_id: userId,
      author_name: username,
      class_tag: tag,
      content: text,
      state,
      date: new Date()
    };
    console.log(params);
    query('insert into article set ?', params, function (err, rows, field) {
      if (err) {
        const json = {
          code: false,
          message: err.message
        };
        console.log(json);
        res.json(json);
      } else {
        const json = {
          code: true,
          message: "文章发表成功"
        };
        console.log(json);
        res.json(json);
      }
    });
  });

  //获取文章
  app.get('/travelarticle', function (req, res, next) {
    let { artId } = req.query;
    if (artId) {
      let sql = `select * from article where id=${artId}`;
      query(sql, function (err, rows, fields) {
        if (err) {
          const json = {
            code: false,
            message: err.message
          };
          console.log(json);
          res.json(json);
        } else {
          if (rows && rows.length > 0) {
            const json = {
              code: true,
              message: '文章获取成功',
              data:new Object(rows[0])
            };
            console.log(json);
            res.json(json);
          } else {
            const json = {
              code: false,
              message: '相关文章不存在',
              data
            };
            console.log(json);
            res.json(json);
          }
        }
      });
    } else {
      const json = {
        code: false,
        message: "请提交正确的文章编号"
      };
      console.log(json);
      res.json(json);
    }
  });

  /**
   * 发表评论
   * 
   * artId(文章Id)
   * username(评论人)
   * content(评论内容)
   */
  app.post('/sendcomment', function (req, res, next) {
    console.log('发表评论成功');
    const { artId, username, content } = req.body;
    const comment = { art_id: artId, author_name: username, content: content, create_time: new Date() };
    query(`insert into comment  set ?`, comment, function (err, data, field) {
      if (err) {
        const json = {
          code: false,
          message: err.message
        };
        console.log(json);
        res.json(json);
      } else {
        const json = {
          code: true,
          message: '发表成功',
          data
        };
        console.log(json);
        res.json(json);
      }
    });
  });

  /**
   * 根据文章id获取评论
   * 
   * artId(文章Id)
   * 
   */
  app.get('/getcommentByArtId', function (req, res, next) {
    query(`select * from comment where art_id`, [req.body.artId], function (err, data, field) {
      if (err) {
        const json = {
          code: false,
          message: err.message
        };
        console.log(json);
        res.json(json);
      } else {
        const json = {
          code: true,
          message: '发表成功',
          data
        };
        console.log(json);
        res.json(json);
      }
    });
  });
};
